package com.mszlu.blog.service.mq;

import com.alibaba.fastjson.JSON;
import com.mszlu.blog.service.ArticleService;
import com.mszlu.blog.vo.Result;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: lfw
 * @Date: 2022/06/09/20:51
 * @Description:
 */
@Component
public class RabbitConsumer {
    @Autowired
    private ArticleService articleService;
    @Autowired

    private RedisTemplate<String, String> redisTemplate;
    @RabbitListener(queues = {"demo"})
    public void consume(@Payload String body, Channel channel) throws Exception {
        System.out.println("接收到消息：" + body);
        //channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        String params=DigestUtils.md5Hex(body);
        String key="view_article::ArticleController::findArticleById::"+params;
        Result article = articleService.findArticleById(Long.parseLong(body),null);
        redisTemplate.opsForValue().set(key, JSON.toJSONString(article), Duration.ofMillis(5 * 60 * 1000));
        Set<String> keys = redisTemplate.keys("listArticle*");
        keys.forEach(s -> {
            redisTemplate.delete(s);
        });
    }
}


